package com.demo.rabbitmq.amqp.cons;

import com.demo.rabbitmq.amqp.entity.Order;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author sc
 * Created on  2018/9/22
 */
@Component

public class RabbitConsumer {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "test_sb",durable = "true"),
            exchange = @Exchange(value = "sb_ex",type = "topic"),
            key = "sb.#"
    ))
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws IOException {
        System.out.println(new String(message.getBody()));
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,false);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${rabbitmq.order.queue}",durable = "true"),
            exchange = @Exchange(value = "${rabbitmq.order.exchange}",type = "topic"),
            key = "${rabbitmq.order.routingKey}"
    ))
    @RabbitHandler
    public void onOrderMessage(@Payload Order order, @Headers Map<String,Object> headers, Channel channel) throws IOException {
        System.out.println(order);
        channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG),false);
    }
}
